package superconfig

import (
	"github.com/samuel/go-zookeeper/zk"
	"time"
)

const AuthUser = "zkr"
const AuthPwd = "gDqI4s7TidXcVSqW"

type ZkClient struct {
	ConnectString []string
	ZkConn        *zk.Conn
	zkAcl         []zk.ACL
}

func NewZkClient(connectString []string) *ZkClient {
	client := ZkClient{
		ConnectString: connectString[:],
		ZkConn:        nil,
		zkAcl:         zk.DigestACL(zk.PermAll, AuthUser, AuthPwd),
	}
	return &client
}

func (client *ZkClient) Close() error {
	if client.ZkConn != nil {
		client.ZkConn.Close()
	}
	return nil
}

func (client *ZkClient) Connect(timeout time.Duration) error {
	if client.ZkConn != nil {
		client.ZkConn.Close()
	}
	c, _, err := zk.Connect(client.ConnectString, timeout)
	if err != nil {
		return err
	}
	auth := AuthUser + ":" + AuthPwd
	if err := c.AddAuth("digest", []byte(auth)); err != nil {
		client.Close()
	}
	client.ZkConn = c
	return nil
}

func (client *ZkClient) Get(path string) ([]byte, error) {
	data, _, err := client.ZkConn.Get(path)
	return data, err
}
